#!/usr/bin/python
# coding=utf-8
import random, sys, logging, time, traceback
# from xpy3lib.utils.XUtils import XUtils
# from datetime import datetime
from datetime import date
from flask import Flask, request, json, jsonify, abort, make_response
import sys, datetime, json, logging, os
import pandas as pd
import numpy as np
from scipy import fftpack

from xpy3lib.utils.XDataFrameUtils import XDataFrameUtils
from xpy3lib.XRetryableQuery import XRetryableQuery

from xpy3lib.utils import db_utils as util
from xpy3lib.XLogger import XLogger
from sicost.config import app_config


app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

profile = (sys.argv[1].split("=", 1)[-1]) if len(sys.argv) > 1 else 'dev'


@app.route('/api-model/get_info.sdo', methods=["GET", "POST"])
def test_index_1():
    response_dict = {'message': 'success---hi--prm-server'}
    return json.dumps(response_dict)


@app.route('/api-model/', methods=["GET", "POST"])
def test_index_0():
    response_dict = {'message': 'success---hi--model-server'}
    return json.dumps(response_dict)


@app.route('/api-model/request_picture.sdo', methods=["GET", "POST"])
def request_model():
    content = dict()
    response_dict = dict()

    body_dict = None
    if request.method == 'POST':
        try:
            try:
                request_json_text = request.get_data()
                body_dict = json.loads(request_json_text.decode('utf-8'))
            except Exception as e:
                body_dict = request.form.to_dict()
                # NOTE below is the pseudo code of post data fetching
                # postdata = request.form['id']
                # file = request.files['file']
        except Exception as e:
            body_dict = None
            traceback.print_exc()
    else:
        body_dict = request.args.to_dict(flat=True)

    #
    if body_dict is not None:
        try:
            # success, msg, remark, timestamp, table_1 = run_model_job(p_body_dict=body_dict)
            code, msg, content, time1, time2, time3, time4, time5, time6, time7, top, frequencyTop, rec_create_time, motor_output = run_model_job(p_body_dict=body_dict)
        except Exception as e:
            code = -100
            msg = f'run_model_job_failed---with--{str(body_dict)}--{str(e)}'
            time1 = time.time()
            time2 = time1
            time3 = time1
            time4 = time1
            time5 = time1
            time6 = time1
            time7 = time1
            top = list()
            frequencyTop = list()
            rec_create_time = ''
            motor_output = ''
    else:
        code = -200
        msg = 'invalid_http_request_parameters'
        time1 = time.time()
        time2 = time1
        time3 = time1
        time4 = time1
        time5 = time1
        time6 = time1
        time7 = time1
        top = list()
        frequencyTop = list()
        rec_create_time = ''
        motor_output = ''
    #总耗时
    elapsed1 = time7 - time1
    #连接STS
    elapsed2 = time3 - time2
    #查询SQL数据
    elapsed3 = time4 - time3
    #关闭STS
    elapsed4 = time5 - time4
    #主体逻辑
    elapsed5 = time6 - time5
    #其他
    elapsed6 = elapsed1 - elapsed2 - elapsed3 - elapsed4 - elapsed5
    #连接存储数据库
    #上传时间
    #关闭连接
    motor_output=str(motor_output)
    response_dict['code'] = code
    response_dict['message'] = msg
    response_dict['rec_create_time'] = rec_create_time
    response_dict['top'] = top
    response_dict['frequencyTop'] = frequencyTop
    response_dict['content'] = content
    response_dict['sum_elapsed'] = elapsed1
    response_dict['connect_sts'] = elapsed2
    response_dict['select_data'] = elapsed3
    response_dict['close_sts'] = elapsed4
    response_dict['main_logic'] = elapsed5
    response_dict['other'] = elapsed6
    now = datetime.datetime.now()
    now_1 = now.strftime('%Y-%m-%d %H:%M:%S')
    response_dict['datetime'] = now_1
    response_dict['motor'] = motor_output
    # return json.dumps(response_dict)
    return bytes(json.dumps(response_dict), 'utf-8')
def run_model_job(p_body_dict):
    """

    """
    #程序开始
    time1 = time.time()
    row_data = p_body_dict
    # tag = row_data[0]['tag']
    # picType = row_data[0]['picType']
    # baseFrequency = row_data[0]['baseFrequency']
    tag = row_data['tag']
    picType = row_data['picType']
    motor = row_data['motor']
    motor_output = motor
    if motor != '':
        motor = int(motor)
        baseFrequency = motor / 60
    else:
        baseFrequency = 0
    if picType == 'all' or picType == 'frequency':
        topMin = row_data['topMin']
        if topMin != '':
            topMinF = float(topMin)
        else:
            topMinF = 0

        topMax = row_data['topMax']
        if topMax != '':
            topMaxF = float(topMax)
            topMaxF = topMaxF * baseFrequency
        else:
            topMaxF = 1000000000000

        topCount = row_data['topCount']
        if topCount != '':
            topCountF = int(topCount)
        else:
            topCountF = 0

        frequencyTop = row_data['frequencyTop']
        if frequencyTop != '':
            frequencyTopF = '"' + frequencyTop + '"'
            frequencyTopF = frequencyTopF.replace(',', '\",\"')
            frequencyTopF = eval(frequencyTopF)
            listF = list(frequencyTopF)
        else:
            listF = list()

        frequencyTopStep = row_data['frequencyTopStep']
        if frequencyTopStep != '':
            frequencyTopStepF = int(frequencyTopStep)
        else:
            frequencyTopStepF = 0
    # tag_list = ['BS_452032E01_MFSIDERBG_HVIB_16K_ACC_WAVE_2000']
    # tag_list = ['BS_436694E11_MFSIDERBG_HVIB_16K_ACC_WAVE_2000','BS_436694E11_MFSIDERBG_HVIB_16K_ACC_WAVE_20000','BS_436694E11_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000','BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_2000','BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_20000','BS_310515E01_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000']
    # data = {'TAG': ['BS_436694E11_MFSIDERBG_HVIB_16K_ACC_WAVE_2000', 'BS_436694E11_MFSIDERBG_HVIB_16K_ACC_WAVE_20000',
    #                 'BS_436694E11_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_20000', 'BS_310515E01_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000'],
    #         'MOTOR': [992, 992, 992, 980, 980, 980]}
    # data = {'TAG': ['BS_310514E01_MBSIDERBG_VVIB_16K_ACC_WAVE_2000', 'BS_310514E01_MBSIDERBG_VVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310514E01_MBSIDERBG_AXVIB_16K_ACC_WAVE_2000', 'BS_310514E01_MBSIDERBG_AXVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310514E01_MFSIDERBG_HVIB_16K_ACC_WAVE_20000', 'BS_310514E01_MFSIDERBG_HVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E01_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_310514E01_MFSIDERBG_VVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E01_MFSIDERBG_VVIB_8K_SPEED_WAVE_1000', 'BS_310514E01_MFSIDERBG_AXVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E01_MFSIDERBG_AXVIB_8K_SPEED_WAVE_1000', 'BS_310514E01_MBSIDERBG_HVIB_16K_ACC_WAVE_20000',
    #                 'BS_310514E01_MBSIDERBG_HVIB_16K_ACC_WAVE_2000', 'BS_310514E01_MBSIDERBG_HVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310514E02_MBSIDERBG_HVIB_16K_ACC_WAVE_20000', 'BS_310514E02_MBSIDERBG_HVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E02_MBSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_310514E02_MBSIDERBG_VVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E02_MBSIDERBG_VVIB_8K_SPEED_WAVE_1000', 'BS_310514E02_MBSIDERBG_AXVIB_16K_ACC_WAVE_2000',
    #                 'BS_310514E02_MBSIDERBG_AXVIB_8K_SPEED_WAVE_1000',
    #                 'BS_361874E01_MBSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_361874E01_MBSIDERBG_VVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310515E01_MBSIDERBG_VVIB_16K_ACC_WAVE_2000', 'BS_310515E01_MBSIDERBG_VVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310515E01_MBSIDERBG_AXVIB_16K_ACC_WAVE_2000', 'BS_310515E01_MBSIDERBG_AXVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_20000', 'BS_310515E01_MFSIDERBG_HVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E01_MFSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_310515E01_MFSIDERBG_VVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E01_MFSIDERBG_VVIB_8K_SPEED_WAVE_1000', 'BS_310515E01_MFSIDERBG_AXVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E01_MFSIDERBG_AXVIB_8K_SPEED_WAVE_1000', 'BS_310515E01_MBSIDERBG_HVIB_16K_ACC_WAVE_20000',
    #                 'BS_310515E01_MBSIDERBG_HVIB_16K_ACC_WAVE_2000', 'BS_310515E01_MBSIDERBG_HVIB_8K_SPEED_WAVE_1000',
    #                 'BS_310515E02_MBSIDERBG_HVIB_16K_ACC_WAVE_20000', 'BS_310515E02_MBSIDERBG_HVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E02_MBSIDERBG_HVIB_8K_SPEED_WAVE_1000', 'BS_310515E02_MBSIDERBG_VVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E02_MBSIDERBG_VVIB_8K_SPEED_WAVE_1000', 'BS_310515E02_MBSIDERBG_AXVIB_16K_ACC_WAVE_2000',
    #                 'BS_310515E02_MBSIDERBG_AXVIB_8K_SPEED_WAVE_1000'],
    #         'MOTOR': [210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   260, 260,
    #                   260, 260,
    #                   260, 260,
    #                   260,
    #                   920, 920,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   210, 210,
    #                   260, 260,
    #                   260, 260,
    #                   260, 260,
    #                   260]}
    # data_tag = pd.DataFrame(data)
    # tag_list = data_tag['TAG'].to_list()
    # if tag in tag_list:
    #     data_tag_1 = data_tag[(data_tag['TAG'] == tag)]
    #     data_tag_1 = data_tag_1.reset_index(drop=True)
    #     motor_tmp = data_tag_1.loc[0]['MOTOR']
    #     if motor != '':
    #         motor_output = motor
    #     else:
    #         motor_output = motor_tmp
    #     time2 = time.time()
    #     time3 = time.time()
    #     #定时程序
    #     path_name = '/apps/reqms/p_project/get_picture/' + str(tag) + '.json'
    #     # path_name = 'D:/repos/sicost/' + str(tag) + '.json'
    #
    #     with open(path_name, 'r', encoding='utf-8') as f:
    #         row_data2 = json.load(f)
    #     if (row_data2 is None):
    #         sys.exit(1)
    #     time4 = time.time()
    #     rec_create_time2 = row_data2['rec_create_time']
    #     content2 = row_data2['content']
    #     if motor == motor_output and topCount == 5 and frequencyTopStep == 2 and frequencyTop == '1,2,3,4,5':
    #         top2 = row_data2['top']
    #         frequencyTop2 = row_data2['frequencyTop']
    #     else:
    #         data_frequency = content2['data_frequency']
    #         df = pd.DataFrame(data_frequency, columns=['axisX', 'axisY'])
    #         #####################现在如果没有转速的话， 就直接把时域、频域、包络的原始数据返回来，不需要计算，1-5倍频的这个倍频的峰值了
    #         top2 = list()
    #         frequencyTop2 = list()
    #         motor = motor_output
    #         motor = int(motor)
    #         baseFrequency = motor / 60
    #         if picType == 'all' or picType == 'frequency':
    #             topMin = row_data['topMin']
    #             if topMin != '':
    #                 topMinF = float(topMin)
    #             else:
    #                 topMinF = 0
    #
    #             topMax = row_data['topMax']
    #             if topMax != '':
    #                 topMaxF = float(topMax)
    #                 topMaxF = topMaxF * baseFrequency
    #             else:
    #                 topMaxF = 1000000000000
    #         # if motor != '':
    #         if topMin != '' and topMax != '':
    #             df_top = df[(df['axisX'] >= topMinF) & (df['axisX'] <= topMaxF)]
    #         elif topMin != '' and topMax == '':
    #             df_top = df[(df['axisX'] >= topMinF)]
    #         elif topMin == '' and topMax != '':
    #             df_top = df[(df['axisX'] <= topMaxF)]
    #         elif topMin == '' and topMax == '':
    #             df_top = df
    #         if topCount != '':
    #             df_top = df_top.sort_values(['axisY'], ascending=False)
    #             df_top = df_top.reset_index(drop=True)
    #             n = topCountF
    #             df_top_n = df_top.iloc[:n]
    #             # print(df_top_n)
    #             top_data = df_top_n.to_json(orient='records', force_ascii=False)
    #             top_data = eval(top_data)
    #             top2 = top_data
    #         else:
    #             top2 = list()
    #         if frequencyTop != '':
    #             for i in range(len(listF)):
    #                 str_tmp = listF[i]
    #
    #                 s = float(str_tmp)
    #                 sb = int(s * (motor / 60))
    #                 df_sb1 = df[(df['axisX'] >= sb)]
    #                 df_sb1 = df_sb1.sort_values(['axisX'], ascending=True)
    #                 df_sb1 = df_sb1.reset_index(drop=True)
    #                 m = frequencyTopStepF + 1
    #                 df_sb1_m = df_sb1.iloc[:m]
    #                 df_sb2 = df[(df['axisX'] <= sb)]
    #                 df_sb2 = df_sb2.sort_values(['axisX'], ascending=False)
    #                 df_sb2 = df_sb2.reset_index(drop=True)
    #                 df_sb2_m = df_sb2.iloc[:m]
    #                 df_sb = pd.concat([df_sb1_m, df_sb2_m], ignore_index=True)
    #                 df_sb = df_sb.sort_values(['axisY'], ascending=False)
    #                 df_sb = df_sb.reset_index(drop=True)
    #                 frequencyTop2.append({'axisX': df_sb.loc[0, 'axisX'],
    #                                      'axisY': df_sb.loc[0, 'axisY']})
    #         else:
    #             frequencyTop2 = list()
    #
    #
    #     time5 = time.time()
    #     code = 0
    #     msg = 'ok'
    #     rec_create_time = rec_create_time2
    #     content = content2
    #     top = top2
    #     frequencyTop = frequencyTop2
    #     time6 = time.time()
    #     time7 = time.time()
    #     return code, msg, content, time1, time2, time3, time4, time5, time6, time7, top, frequencyTop, rec_create_time, motor_output
    # else:
    ######20231129新增接口将STS数据落地
    path_name = '/apps/reqms/p_project/get_picture/sts_data/' + str(tag) + '.json'
    # path_name = 'D:/repos/sicost/' + str(tag) + '.json'
    try:
        with open(path_name, 'r', encoding='utf-8') as f:
            row_data3 = json.load(f)
        if (row_data3 is None):
            sys.exit(1)
        time2 = time.time()
        time3 = time.time()
        time4 = time.time()
        rec_create_time = row_data3['rec_create_time']
        signal_info_hz = row_data3['signal_info_hz']
        signal_info_output = row_data3['signal_info_output']
        signal_value = row_data3['SignalValue']
    except Exception as e:
        profile = 'dev'
        config = app_config[profile]
        #连接数据库开始
        time2 = time.time()

        try:
            db_conn_sts = util.getConnectionSTS(config.DB_HOST_STS2,
                                                config.DB_PORT_STS2,
                                                config.DB_DBNAME_STS2,
                                                config.DB_USER_STS2,
                                                config.DB_PASSWORD_STS2)
            # XLogger.getInstance().logger.info('connect db_conn_sts success')
        except Exception as e:
            db_conn_sts = None
            # XLogger.getInstance().logger.critical(str(e))
        if db_conn_sts is None:
            code = '-300'
            msg = '连接STS失败'
            content = ''
            time3 = time2
            time4 = time2
            time5 = time2
            time6 = time2
            time7 = time2
            top = list()
            frequencyTop = list()
            rec_create_time = ''
            return code, msg, content, time1, time2, time3, time4, time5, time6, time7, top, frequencyTop, rec_create_time, motor_output
        #连接数据库成功，查询SQL数据开始
        time3 = time.time()

        sql = " SELECT * FROM bgtasoemfn.t_motor_signal where tag='%s'  order by rec_create_time desc limit 1 " % (tag)
        # print(sql)
        df_1 = XRetryableQuery(p_db_conn=db_conn_sts, p_sql=sql, p_max_times=5).redo()
        success = df_1.empty is False
        if success is False:
            code = '-400'
            msg = 'STS查询为空'
            content = ''
            time4 = time3
            time5 = time3
            time6 = time3
            time7 = time3
            top = list()
            frequencyTop = list()
            rec_create_time = ''
            return code, msg, content, time1, time2, time3, time4, time5, time6, time7, top, frequencyTop, rec_create_time, motor_output
        #读取SQL获取数据成功
        time4 = time.time()

        signal_info_hz = df_1.loc[0, 'signal_info_hz']
        signal_info_output = df_1.loc[0, 'signal_info_output']
        signal_value = df_1.loc[0, 'signal_value']
        # vib_direction = df_1.loc[0, 'vib_direction']
        rec_create_time = df_1.loc[0, 'rec_create_time']
        #关闭连接
        util.closeConnection(db_conn_sts)

    # else:
    #     time2 = time.time()
    #     time3 = time.time()
    #     time4 = time.time()
    #     rec_create_time = row_data3['rec_create_time']
    #     signal_info_hz = row_data3['signal_info_hz']
    #     signal_info_output = row_data3['signal_info_output']
    #     signal_value = row_data3['SignalValue']
    content = dict()
    #转换作图数据开始
    time5 = time.time()

    if picType == 'all':
        df_time = getcoordinate(p_picType='time',
                                           p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                           p_signal_value=signal_value)
        df_frequency = getcoordinate(p_picType='frequency',
                                p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                p_signal_value=signal_value)
        df_envelope = getcoordinate(p_picType='envelope',
                                     p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                     p_signal_value=signal_value)

        mydata_time = df_time.to_json(orient='records', force_ascii=False)
        mydata_time = eval(mydata_time)
        data_time = mydata_time
        content['data_time'] = data_time
########20231116第一个：以前返回数据时是按照倍频（转速/60）的数据做的最大七倍频的数据量，现在不做这个倍频的限制了
        dfF = df_frequency
###################################################################################
        dfF = dfF.reset_index(drop=True)
        mydata_frequency = dfF.to_json(orient='records', force_ascii=False)
        mydata_frequency = eval(mydata_frequency)
        data_frequency = mydata_frequency
        content['data_frequency'] = data_frequency

        mydata_envelope = df_envelope.to_json(orient='records', force_ascii=False)
        mydata_envelope = eval(mydata_envelope)

        data_envelope = mydata_envelope
        content['data_envelope'] = data_envelope

        top = list()
        frequencyTop = list()
        df = df_frequency
        #####################现在如果没有转速的话，就直接把时域、频域、包络的原始数据返回来，不需要计算，1-5倍频的这个倍频的峰值了
        if motor != '':
            if topMin != '' and topMax != '':
                df_top = df[(df['axisX'] >= topMinF) & (df['axisX'] <= topMaxF)]
            elif topMin != '' and topMax == '':
                df_top = df[(df['axisX'] >= topMinF)]
            elif topMin == '' and topMax != '':
                df_top = df[(df['axisX'] <= topMaxF)]
            elif topMin == '' and topMax == '':
                df_top = df
            if topCount != '':
                df_top = df_top.sort_values(['axisY'], ascending=False)
                df_top = df_top.reset_index(drop=True)
                n = topCountF
                df_top_n = df_top.iloc[:n]
                # print(df_top_n)
                top_data = df_top_n.to_json(orient='records', force_ascii=False)
                top_data = eval(top_data)
                top = top_data
            else:
                top = list()


            if frequencyTop != '':
                for i in range(len(listF)):
                    str_tmp = listF[i]

                    s = float(str_tmp)
                    sb = int(s * (motor / 60))
                    df_sb1 = df[(df['axisX'] >= sb)]
                    df_sb1 = df_sb1.sort_values(['axisX'], ascending=True)
                    df_sb1 = df_sb1.reset_index(drop=True)
                    m = frequencyTopStepF + 1
                    df_sb1_m = df_sb1.iloc[:m]
                    df_sb2 = df[(df['axisX'] <= sb)]
                    df_sb2 = df_sb2.sort_values(['axisX'], ascending=False)
                    df_sb2 = df_sb2.reset_index(drop=True)
                    df_sb2_m = df_sb2.iloc[:m]
                    df_sb = pd.concat([df_sb1_m, df_sb2_m], ignore_index=True)
                    df_sb = df_sb.sort_values(['axisY'], ascending=False)
                    df_sb = df_sb.reset_index(drop=True)
                    frequencyTop.append({'axisX': df_sb.loc[0, 'axisX'],
                                         'axisY': df_sb.loc[0, 'axisY']})
            else:
                frequencyTop = list()




    else:
        df = getcoordinate(p_picType=picType,
                                           p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                           p_signal_value=signal_value)
        top = list()
        frequencyTop = list()
        if picType == 'frequency':
            if topMin != '' and topMax != '':
                df_top = df[(df['axisX'] >= topMinF) & (df['axisX'] <= topMaxF)]
            elif topMin != '' and topMax == '':
                df_top = df[(df['axisX'] >= topMinF)]
            elif topMin == '' and topMax != '':
                df_top = df[(df['axisX'] <= topMaxF)]
            elif topMin == '' and topMax == '':
                df_top = df
########20231116第一个：以前返回数据时是按照倍频（转速/60）的数据做的最大七倍频的数据量，现在不做这个倍频的限制了
            df = df
###################################################################################
            df = df.reset_index(drop=True)
#####################现在如果没有转速的话，就直接把时域、频域、包络的原始数据返回来，不需要计算，1-5倍频的这个倍频的峰值了
            if motor != '':
                if topCount != '':
                    df_top = df_top.sort_values(['axisY'], ascending=False)
                    df_top = df_top.reset_index(drop=True)
                    n = topCountF
                    df_top_n = df_top.iloc[:n]
                    top_data = df_top_n.to_json(orient='records', force_ascii=False)
                    top_data = eval(top_data)
                    top = top_data
                else:
                    top = list()

                if frequencyTop != '':
                    for i in range(len(listF)):
                        str_tmp = listF[i]
                        s = float(str_tmp)
                        sb = int(s * (motor / 60))
                        df_sb1 = df[(df['axisX'] >= sb)]
                        df_sb1 = df_sb1.sort_values(['axisX'], ascending=True)
                        df_sb1 = df_sb1.reset_index(drop=True)
                        m = frequencyTopStepF + 1
                        df_sb1_m = df_sb1.iloc[:m]
                        df_sb2 = df[(df['axisX'] <= sb)]
                        df_sb2 = df_sb2.sort_values(['axisX'], ascending=False)
                        df_sb2 = df_sb2.reset_index(drop=True)
                        df_sb2_m = df_sb2.iloc[:m]
                        # df_sb0 = df[(df['axisX'] == sb)]
                        df_sb = pd.concat([df_sb1_m, df_sb2_m], ignore_index=True)
                        df_sb = df_sb.sort_values(['axisY'], ascending=False)
                        df_sb = df_sb.reset_index(drop=True)

                        frequencyTop.append({'axisX': df_sb.loc[0, 'axisX'],
                                             'axisY': df_sb.loc[0, 'axisY']})
                else:
                    frequencyTop = list()





        mydate = df.to_json(orient='records', force_ascii=False)
        mydate = eval(mydate)
        data = mydate
        content['data'] = data



    #作图数据生成完成
    time6 = time.time()


    code = 0
    msg = 'ok'

    # util.closeConnection(db_conn_sts)
    #关闭数据库完成
    time7 = time.time()


    return code, msg, content, time1, time2, time3, time4, time5, time6, time7, top, frequencyTop, rec_create_time, motor_output


def getcoordinate(p_picType, p_signal_info_hz, p_signal_info_output, p_signal_value):
    p_signal_value = eval(p_signal_value)

    x = [float(v) for v in p_signal_value]
    sampling_rate = p_signal_info_hz  # 取样频率(来自传感器说明书)
    fft_size = p_signal_info_output  # FFT处理的数据样本数
    xt = np.asarray(x)
    xt = xt - np.mean(xt)  # 去直流分量
    if p_picType == 'time':
        tstemp = np.linspace(0, int(1e6 / sampling_rate * fft_size), fft_size) / 1e3
        arr3 = np.vstack((tstemp, xt))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])
    if p_picType == 'frequency':
        am = np.fft.fft(xt)  # 对希尔伯特变换后的at做fft变换获得幅值
        am = np.abs(am)  # 对幅值求绝对值（此时的绝对值很大）
        am = am / len(am) * 2
        am = am[0: int(len(am) / 2)]
        freq = np.fft.fftfreq(len(xt), d=1 / sampling_rate)  # 获取fft频率，此时包括正频率和负频率
        freq = freq[0:int(len(freq) / 2)]  # 获取正频率
        arr3 = np.vstack((freq, am))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])

    if p_picType == 'envelope':
        ht = fftpack.hilbert(xt)
        at = np.sqrt(ht ** 2 + xt ** 2)  # at = sqrt(xt^2 + ht^2)
        sampling_rate = sampling_rate
        at = at - np.mean(at)  # 去直流分量
        am = np.fft.fft(at)  # 对希尔伯特变换后的at做fft变换获得幅值
        am = np.abs(am)  # 对幅值求绝对值（此时的绝对值很大）
        am = am / len(am) * 2
        am = am[0: int(len(am) / 2)]
        freq = np.fft.fftfreq(len(at), d=1 / sampling_rate)  # 获取fft频率，此时包括正频率和负频率
        freq = freq[0:int(len(freq) / 2)]  # 获取正频率
        arr3 = np.vstack((freq, am))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])
    return df


if __name__ == '__main__':

    app.run(host='0.0.0.0', port=7078)
